package solution;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-21
 * Time: 15:59
 */

//https://leetcode.cn/problems/find-words-that-can-be-formed-by-characters/submissions/396574782/
class Solution3 {
    public int countCharacters(String[] words, String chars) {
        //少量的字符直接数组模拟哈希表，比api更快
        int[] charsArr = new int[26];
        for (int i = 0; i < chars.length(); i++) {
            charsArr[chars.charAt(i) - 'a']++;
        }
        int count = 0;
        for (String word : words) {
            int wordLen = word.length();
            int[] wordArr = new int[26];
            for (int i = 0; i < wordLen; i++) {
                wordArr[word.charAt(i) - 'a']++;
            }
            boolean flag = true;
            for (int j = 0; j < wordLen; j++) {
                if (charsArr[word.charAt(j) - 'a'] < wordArr[word.charAt(j) - 'a']) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                count += wordLen;
            }
        }
        return count;
    }
}
